<template>
	<view class="upload-container">
		<!-- 图片上传区域 -->
		<view class="upload-area" @click="chooseImage">
			<view class="upload-icon">
				<uni-icons type="camera" size="60" color="#999"></uni-icons>
			</view>
			<view class="upload-text">点击上传图片</view>
			<view class="upload-desc">支持JPG、PNG格式，不超过5MB</view>
		</view>

		<!-- 已选择图片预览 -->
		<view class="preview-container" v-if="imageList.length > 0">
			<view class="preview-title">已选择 {{ imageList.length }} 张图片</view>
			<view class="image-grid">
				<view class="image-item" v-for="(img, index) in imageList" :key="index">
					<image :src="img" mode="aspectFill" class="preview-img" @click="previewImage(index)"></image>
					<view class="delete-btn" @click.stop="deleteImage(index)">
						<uni-icons type="clear" size="24" color="#fff"></uni-icons>
					</view>
				</view>
			</view>
		</view>

		<!-- 上传按钮 -->
		<button class="upload-btn" :loading="isUploading" @click="uploadImages">
			{{ isUploading ? '上传中...' : '确认上传' }}
		</button>

		<!-- 上传进度 -->
		<!-- 	<view class="progress-container" v-if="showProgress">
			<uni-progress :percent="uploadProgress" stroke-width="6" activeColor="#07c160"></uni-progress>
			<view class="progress-text">{{ uploadProgress }}% 已完成</view>
		</view> -->
	</view>
</template>

<script setup>
	import {
		ref,
		computed
	} from 'vue'
	import {
		onLoad
	} from '@dcloudio/uni-app'
	import {
		useToast
	} from 'wot-design-uni'
	import {
		getEnvBaseUrl
	} from '@/utils/index'
	// 图片相关状态
	const imageList = ref([]) // 已选择的图片列表
	const maxCount = ref(5) // 最大选择数量
	const isUploading = ref(false) // 是否正在上传
	const uploadProgress = ref(0) // 上传进度
	const showProgress = ref(false) // 是否显示进度条
	const uploadPath = `${getEnvBaseUrl()}/sys/common/upload`;

	// 计算属性：是否还能继续选择图片
	const canChooseMore = computed(() => {
		return imageList.value.length < maxCount.value
	})

	// 页面加载时初始化
	onLoad(() => {
		// 可在这里初始化上传相关配置
	})

	// 选择图片
	const chooseImage = () => {
		if (!canChooseMore.value) {
			uni.showToast({
				title: '最多只能选择53张图片',
				icon: 'none'
			})
			return
		}

		uni.chooseImage({
			count: maxCount.value - imageList.value.length, // 剩余可选择数量
			sizeType: ['original', 'compressed'], // 原图/压缩图
			sourceType: ['album', 'camera'], // 相册/相机
			success: (res) => {
				// 将选择的图片临时路径添加到列表
				imageList.value = [...imageList.value, ...res.tempFilePaths]
				const tempFilePaths = res.tempFilePaths;
				const file = res.tempFiles[0]; // 获取文件信息对象
				// 判断文件大小（示例：限制不超过 5MB，1MB = 1024*1024 字节）
				const maxSize = 5 * 1024 * 1024;
				if (file.size > maxSize) {
					uni.showToast({
						title: '文件大小不能超过5MB',
						icon: 'none'
					});
					return; // 不执行上传
				}
			},
			fail: (err) => {
				console.error('选择图片失败', err)
				uni.showToast({
					title: '选择图片失败，请重试',
					icon: 'none'
				})
			}
		})
	}

	// 预览图片
	const previewImage = (index) => {
		uni.previewImage({
			current: imageList.value[index], // 当前预览图片
			urls: imageList.value, // 所有预览图片
			loop: true // 支持循环预览
		})
	}

	// 删除图片
	const deleteImage = (index) => {
		imageList.value.splice(index, 1)
	}

	// 上传图片到服务器
	const uploadImages = async () => {
		if (imageList.value.length === 0) return
		isUploading.value = true
		showProgress.value = true
		uploadProgress.value = 0
		console.log(uploadPath)
		console.log("*******url********")

		try {
			// 多张图片依次上传
			const uploadResults = []
			const total = imageList.value.length

			for (let i = 0; i < total; i++) {
				const tempFilePath = imageList.value[i]

				// 调用上传API
				const uploadRes = await new Promise((resolve, reject) => {
					uni.uploadFile({
						url: uploadPath, // 替换为实际接口地址
						filePath: tempFilePath,
						"biz": "testpath",
						name: 'file', // 后端接收文件的字段名
						formData: {
							// 额外的表单数据
							type: 'avatar',
							timestamp: Date.now()
						},
						// 上传进度回调
						progress: (progressEvent) => {
							const percent = Math.floor((i * 100 + progressEvent.progress) /
								total)
							uploadProgress.value = percent
						},
						success: (res) => {
							// 解析服务器返回结果
							console.log("********success**************")
							console.log(res)
							isUploading.value = false
							if (res.success) {
								// resolve(data.data) // 假设返回图片URL
							} else {
								// reject(new Error(data.msg || '上传失败'))
							}
						},
						fail: (err) => {
							reject(err)
						}
					})
				})

				uploadResults.push(uploadRes)
			}

			// 所有图片上传成功
			uploadProgress.value = 100

			uni.showToast({
				title: '全部图片上传成功',
				icon: 'none'
			})
			// 可以在这里处理上传成功后的逻辑，如返回图片URL列表
			console.log('上传结果', uploadResults)

			// 清空列表（根据需求决定是否保留）
			setTimeout(() => {
				imageList.value = []
				showProgress.value = false
				isUploading.value = false
			}, 1000)

		} catch (err) {
			console.error('上传失败', err)
			uni.showToast({
				title: '上传失败，请重试',
				icon: 'none'
			})
			isUploading.value = false
			showProgress.value = false
		}
	}

	// 上传到微信云存储（如果使用云开发）
	const uploadToCloud = async () => {
		if (imageList.value.length === 0) return

		isUploading.value = true
		showProgress.value = true
		uploadProgress.value = 0

		try {
			const uploadResults = []
			const total = imageList.value.length

			for (let i = 0; i < total; i++) {
				const tempFilePath = imageList.value[i]

				// 生成云存储路径
				const cloudPath = `images/${Date.now()}-${i}.${tempFilePath.split('.').pop()}`

				// 调用云上传API
				const uploadRes = await uniCloud.uploadFile({
					cloudPath,
					fileContent: tempFilePath,
					onUploadProgress: (progressEvent) => {
						const percent = Math.floor((i * 100 + progressEvent.progress) / total)
						uploadProgress.value = percent
					}
				})

				if (uploadRes.fileID) {
					uploadResults.push(uploadRes.fileID)
				} else {
					throw new Error('云存储上传失败')
				}
			}

			// 所有图片上传成功
			uploadProgress.value = 100
			uni.showToast({
				title: '全部图片上传成功',
				icon: 'none'
			})
			console.log('云存储文件ID列表', uploadResults)

			// 清空列表
			setTimeout(() => {
				imageList.value = []
				showProgress.value = false
				isUploading.value = false
			}, 1000)

		} catch (err) {
			console.error('云上传失败', err)
			uni.showToast({
				title: '上传失败，请重试',
				icon: 'none'
			})
			isUploading.value = false
			showProgress.value = false
		}
	}
</script>

<style scoped>
	.upload-container {
		padding: 30rpx;
		display: flex;
		flex-direction: column;
		gap: 20rpx;
	}

	/* 上传区域样式 */
	.upload-area {
		width: 100%;
		height: 200rpx;
		border: 2rpx dashed #ccc;
		border-radius: 16rpx;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		background-color: #f9f9f9;
		cursor: pointer;
	}

	.upload-icon {
		margin-bottom: 15rpx;
	}

	.upload-text {
		font-size: 30rpx;
		color: #333;
		margin-bottom: 5rpx;
	}

	.upload-desc {
		font-size: 24rpx;
		color: #999;
	}

	/* 预览区域样式 */
	.preview-container {
		display: flex;
		flex-direction: column;
		gap: 15rpx;
	}

	.preview-title {
		font-size: 28rpx;
		color: #666;
	}

	.image-grid {
		display: flex;
		flex-wrap: wrap;
		gap: 15rpx;
	}

	.image-item {
		width: 160rpx;
		height: 160rpx;
		position: relative;
		border-radius: 8rpx;
		overflow: hidden;
	}

	.preview-img {
		width: 100%;
		height: 100%;
	}

	.delete-btn {
		position: absolute;
		top: 0;
		right: 0;
		width: 40rpx;
		height: 40rpx;
		background-color: rgba(255, 0, 0, 0.7);
		display: flex;
		justify-content: center;
		align-items: center;
	}

	/* 按钮样式 */
	.upload-btn {
		width: 100%;
		height: 80rpx;
		line-height: 80rpx;
		background-color: #07c160;
		color: #fff;
		border-radius: 40rpx;
		font-size: 32rpx;
		margin-top: 20rpx;
	}

	/* 进度条样式 */
	.progress-container {
		margin-top: 20rpx;
		display: flex;
		flex-direction: column;
		gap: 10rpx;
	}

	.progress-text {
		font-size: 26rpx;
		color: #666;
		text-align: center;
	}
</style>